<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="card-box">
      <el-alert title="注意：只允许为末尾子分类设置相关参数！"
        type="warning"
        show-icon
        :closable="false">
      </el-alert>
      <span>选择商品分类：</span>
      <el-cascader :options="categories" :props="cascaderProps"
        v-model="selectCateIds"
        @change="handleCateSelect"
      ></el-cascader>
      <!-- 标签页 -->
      <el-tabs v-model="activeTabName" @tab-click="getAttributeList">
        <el-tab-pane label="静态参数" name="only">
          <!-- 自定义参数面板 -->
          <param-pane
            :cateId="cateId" :attrList="onlyAttrList"
            @handleAddDialOpen="addDialogVisable = true"
            @handleEditDialOpen="handleEditDialOpen"
            @handleAttrValAdd="handleAttrValAdd"
            @handleAttrValDel="handleAttrValDel"
            @showAttrInput="showAttrInput"
            @handleAttrDel="handleAttrDel"
          ></param-pane>
        </el-tab-pane>
        <el-tab-pane label="动态参数" name="many">
            <!-- 自定义参数面板 -->
          <param-pane
            :cateId="cateId" :attrList="manyAttrList"
            @handleAddDialOpen="addDialogVisable = true"
            @handleEditDialOpen="handleEditDialOpen"
            @handleAttrValAdd="handleAttrValAdd"
            @handleAttrValDel="handleAttrValDel"
            @showAttrInput="showAttrInput"
            @handleAttrDel="handleAttrDel"
          ></param-pane>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加弹框 -->
    <el-dialog :title="'添加'+tabTitle"
      :visible.sync="addDialogVisable"
      @close="handleAddDialClose"
    >
      <el-form :model="attrAddForm" :rules="attrRules" ref="attrAddFormRef" label-width="100px">
        <el-form-item prop="attr_name" label="属性" required="">
          <el-input v-model="attrAddForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <el-button @click="addDialogVisable = false">取 消</el-button>
        <el-button type="primary" @click="handleAttrAdd">确 定</el-button>
      </template>
    </el-dialog>
  
    <!-- 编辑弹框 -->
    <el-dialog :title="'编辑'+tabTitle"
      :visible.sync="editDialogVisable"
      @close="handleEditDialClose"
    >
      <el-form :model="attrEditForm" :rules="attrRules" ref="attrEditFormRef" label-width="100px">
        <el-form-item prop="attr_name" label="属性" required="">
          <el-input v-model="attrEditForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <el-button @click="editDialogVisable = false">取 消</el-button>
        <el-button type="primary" @click="handleAttrUpdate">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import {
  getAttributesByCateId,
  addAttribute,
  updateAttribute,
  deleteAttribute 
} from '../../../api/params'
import {getCategories} from '../../../api/cates'
import {splitBy} from '../../../utils/util'
import paramPane from './paramPane'
export default {
  components:{
    'param-pane':paramPane
  },
  created(){
    this.getCateList()
  },
  data(){
    return{
      categories:[],
      cascaderProps:{
        value:'cat_id',
        label:'cat_name',
        children:'children'
      },
      // 级联器选择的id
      selectCateIds:[],
      // 标签名
      activeTabName:'only',
      // 属性列表
      onlyAttrList:[],
      manyAttrList:[],
      // 是否已请求数据
      isOnlyGeted:false,
      isManyGeted:false,
      // 属性添加和编辑
      addDialogVisable:false,
      editDialogVisable:false,
      attrAddForm:{
        attr_name:'',
        attr_sel:''
      },
      attrEditForm:{
        attr_id:-1,
        attr_name:'',
        attr_sel:''
      },
      attrRules:{
        attr_name:{ required: true, message: '请输入属性名称', trigger: 'blur' },
      }
    }
  },
  computed:{
      cateId(){
        return this.selectCateIds.length?this.selectCateIds[this.selectCateIds.length-1]:-1
      },
      tabTitle(){
        if(this.activeTabName === 'many'){
          return '动态属性'
        }else if(this.activeTabName === 'only'){
          return '静态属性'
        }
      }
  },
  methods:{
    // 获取商品分类
    async getCateList(){
      try {
        const res = await getCategories()
        this.categories = res.data
      } catch (err) {
        console.log(err);
      }
    },
    // 选中商品分类
    handleCateSelect(){
      this.isOnlyGeted = false
      this.isManyGeted = false
      this.manyAttrList = []
      this.onlyAttrList = []
      this.getAttributeList()
    },
    // 处理属性数据
    dealAttrData(item){
      item.attrValArr = splitBy(item.attr_vals,' ')
      item.inputVisable = false
      item.inputValue = ''
    },
    // 重新拉取数据
    retriveData(){
      if(this.activeTabName==='only')
        this.isOnlyGeted=false
      else if(this.activeTabName==='many')
        this.isManyGeted=false
      this.getAttributeList()
    },

    // 获取属性列表
    async getAttributeList(){
      if(this.cateId < 0){
        return
      }
      //已经获取过only属性数据or获取过many属性
      if((this.activeTabName==='only' && this.isOnlyGeted===true)
        || (this.activeTabName==='many' && this.isManyGeted===true)){
        return 
      }
      // console.log('获取属性列表');
      try {
          const res = await getAttributesByCateId(this.cateId,{
            sel:this.activeTabName
          })
          res.data.forEach(item=>{
            this.dealAttrData(item)
          })


          if(this.activeTabName==='only'){
            this.onlyAttrList = res.data
            this.isOnlyGeted = true
          }else if(this.activeTabName==='many'){
            this.manyAttrList = res.data
            this.isManyGeted = true
          }
        } catch (err) {
          console.log(err);
        }
    },
    // 显示属性输入框
    showAttrInput(row,that){
      row.inputVisable = true
      // 下一次DOM更新后,聚焦到input组件上
      this.$nextTick(_=>{
        that.$refs['attrInput'+this.cateId+row.attr_id].focus()
        // that.$refs.attrInput.$refs.input.focus() //这种方式也可以
      })
    },
    // 修改属性
    async updateAttrVal(row,data){
      try {
        const res = await updateAttribute(this.cateId,row.attr_id,data)
        row.attr_vals = res.data.attr_vals
        row.attrValArr = splitBy(res.data.attr_vals,' ') 
        this.$message({
          type:'success',
          message:res.meta.msg
        })
      } catch (err) {
        console.log(err);
      }
    },
    // 添加属性值
    handleAttrValAdd(row){
      const value = row.inputValue.trim()
      row.inputVisable = false
      row.inputValue = ''
      if(!value){ //如果为空
        return this.$message('取消添加，输入不能为空或全空格！')
      } 
      if(row.attrValArr.includes(value)){ //如果值重复
        return this.$message('取消添加，属性值已存在！')
      }
      
      const data = {
          ...row,
          attr_vals:[...row.attrValArr, value].join(' '),
      }
      delete data.attrValArr
      delete data.inputValue
      delete data.inputVisable
      this.updateAttrVal(row,data)
    },
    // 删除属性值
    handleAttrValDel(row,delVal){
      this.$confirm('此操作将永久删除该属性值, 是否继续?','删除属性值',{
        type:'warning'
      }).then(_=>{
        const newAttrVals = row.attrValArr.filter(item=>{
          return item !== delVal
        })
        // console.log(newAttrVals);
        const data = {
            ...row,
            attr_vals: newAttrVals.join(' '),
        }
        delete data.attrValArr
        delete data.inputValue
        delete data.inputVisable
        this.updateAttrVal(row,data)
      }).catch(_=>{
        this.$message('取消删除属性值')
      })
      
    },
    // 处理添加框和编辑框关闭
    handleAddDialClose(){
      this.$refs.attrAddFormRef.resetFields()
    },
    handleEditDialClose(){
      this.$refs.attrEditFormRef.resetFields()
    },
    // 添加属性
    async handleAttrAdd(){
      this.attrAddForm.attr_sel = this.activeTabName
      // console.log(this.attrAddForm);
      try {
        const res = await addAttribute(this.cateId,this.attrAddForm)
        const result = res.data
        this.dealAttrData(result)
        this.addDialogVisable = false
        this.$message({
          type:'success',
          message:res.meta.msg
        })
        if(this.activeTabName==="only"){
          this.onlyAttrList.unshift(result)
        }else if(this.activeTabName==="many"){
          this.manyAttrList.unshift(result)
        }
      } catch (err) {
        console.log(err);
      }
    },
    // 打开编辑框
    handleEditDialOpen(row){
      this.editDialogVisable = true
      this.attrEditForm.attr_id = row.attr_id
      this.attrEditForm.attr_name = row.attr_name
    },
    // 更新属性 
    async handleAttrUpdate(){
      this.attrEditForm.attr_sel = this.activeTabName
      try {
        const res = await updateAttribute(this.cateId,this.attrEditForm.attr_id,this.attrEditForm)
        // console.log(res.data);

        this.editDialogVisable = false
        this.$message({
          type:'success',
          message:res.meta.msg
        })
        // 重新拉取数据
        this.retriveData()
      } catch (err) {
        console.log(err);
      }
    },
    // 删除属性
    handleAttrDel(attrId){
      this.$confirm('此操作将永久删除该参数信息, 是否继续?','删除'+this.tabTitle,{
        type:'warning'
      }).then(async _=>{
        try {
          const res = await deleteAttribute(this.cateId,attrId)
          this.$message({
            type:'success',
            message:res.meta.msg
          })
          this.retriveData()
        } catch (err) {
          console.log(err);
        }
      }).catch(_=>{
        this.$message('取消删除属性')
      })
    }
   
  }
}
</script>
<style scoped>
.el-alert{
  margin-bottom: 20px;
}

</style>